package com.lq.pc.webmagic;

import lombok.extern.slf4j.Slf4j;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.pipeline.ConsolePipeline;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Selectable;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class GithubRepoPageProcessor implements PageProcessor {

    private Site site = Site.me().setRetryTimes(3).setSleepTime(1);

    @Override
    public void process(Page page) {

        List<Selectable> nodes = page.getHtml().$("div#live-list-content").$("ul#live-list-contentbox").$("li").nodes();
        List<String> names = new ArrayList<>();
        List<String> counts = new ArrayList<>();

        nodes.forEach(e -> {
            String name = e.$("a").$("div.mes").$("p").$("span").xpath("//span[@class='dy-name ellipsis fl']/text()").get();
            String count = e.$("a").$("div.mes").$("p").$("span").xpath("//span[@class='dy-num fr']/text()").get();
            names.add(name);
            counts.add(count);
        });
        page.putField("names", names);
        page.putField("counts", counts);
        if (page.getResultItems().get("names") == null) {
            page.setSkip(true);
        } else {
            ResultItems resultItems = page.getResultItems();
        }
    }

    @Override
    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {
        Spider.create(new GithubRepoPageProcessor()).addUrl("https://www.douyu.com/g_LOL").addPipeline(new ConsolePipeline()).thread(5).run();
    }
}